package com.haibei.view;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Dialog;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.common.net.NetResult;
import com.common.task.BaseTask;
import com.common.task.NetCallBack;
import com.common.uitl.ListUtiles;
import com.common.uitl.LogUtil;
import com.common.uitl.Tool;
import com.haibei.App;
import com.haibei.R;
import com.haibei.activity.MainActivity;
import com.haibei.activity.topic.TopicDetailActivity;
import com.haibei.adapter.TopicAdapter;
import com.haibei.adapter.bean.Topic;
import com.haibei.net.NetInterface;
import com.haibei.view.PullToRefreshView.OnFooterRefreshListener;
import com.haibei.view.PullToRefreshView.OnHeaderRefreshListener;

/**
 * 话题页面
 * 
 * @author wangzy
 */
public class SubTabViewTopic extends SubTabView implements View.OnClickListener, OnHeaderRefreshListener, OnFooterRefreshListener {

	private PullToRefreshView mPullToRefreshView;
	private ListView mlistViewTopics;
	private ArrayList<Topic> mArrayList;
	private TopicAdapter mAdapter;
	private BaseTask mBaseTask;
	private final int page_size = 10;
	private final int INT_RTYPE_FIRST = 1;
	private final int INT_RTYPE_REFRESH = 2;
	private final int INT_RTYPE_LODMORE = 3;

	private View headerView;
	public Topic currentTopic;

	public SubTabViewTopic(MainActivity activity) {
		super(activity);
	}

	@Override
	public void initView() {
		this.mContentView = View.inflate(mActivity, R.layout.sub_tab_topic, null);
		mArrayList = new ArrayList<Topic>();
		mlistViewTopics = (ListView) findViewById(R.id.listViewTopics);
		mPullToRefreshView = (PullToRefreshView) findViewById(R.id.main_pull_refresh_view);
		mPullToRefreshView.setOnHeaderRefreshListener(this);
		mPullToRefreshView.setOnFooterRefreshListener(this);
		createheaderView();
	}

	@Override
	public void onShow() {
		getActivity().getSlidingMenu().setSlidingEnabled(false);
		if (ListUtiles.isEmpty(mArrayList)) {
			requestData(INT_RTYPE_FIRST, mArrayList.size());
		}
	}

	private void requestData(int type, int offset) {
		HashMap<String, String> hmap = new HashMap<String, String>();
		hmap.put("offset", String.valueOf(offset));
		hmap.put("limit", String.valueOf(page_size));
		getRequestTask(type).execute(hmap);
	}

	private BaseTask getRequestTask(final int type) {
		if (null != mBaseTask && !mBaseTask.isCancelled()) {
			mBaseTask.cancel(true);
		}
		mBaseTask = new BaseTask(new NetCallBack() {

			@Override
			public void onPreCall() {
				if (INT_RTYPE_FIRST == type) {
					getActivity().showProgressDialogWithTask(mBaseTask);
				}
			}

			@Override
			public void onFinish(NetResult result) {
				if (INT_RTYPE_FIRST == type) {
					getActivity().hideProgressDialogWithTask();
				}
				if (null != result) {
					if (result.isSuccess()) {
						ArrayList<Topic> list = (ArrayList<Topic>) (result.getData()[0]);
						Object top = result.getData()[1];
						if (null != top) {
							updateHeader((Topic) top);
						} else {
							if (!ListUtiles.isEmpty(list)) {
								updateHeader(list.get(0));
							}
						}
						buildConsultAdapter(list, type);
					} else {
						Tool.ToastShow(getActivity(), result.getMessage());
					}
				} else {
					showRetryDailog(type, getActivity().getResources().getString(R.string.error_net), true);// 展示重试
				}
			}

			@Override
			public NetResult onDoInBack(HashMap<String, String> paramMap) {
				NetResult result = null;
				try {
					result = NetInterface.listTopic(getActivity(), paramMap);
				} catch (Exception e) {
				}
				return result;
			}
		});
		return mBaseTask;
	}

	// 展示重试对话框
	private void showRetryDailog(final int type, String message, boolean isEnableCancell) {
		final Dialog dialog = new Dialog(getActivity(), R.style.Translucent_NoTitle);
		dialog.setCancelable(isEnableCancell);
		View viewWaring = View.inflate(getActivity(), R.layout.dialog_retry, null);
		TextView textViewTitle = (TextView) viewWaring.findViewById(R.id.textViewTitle);
		textViewTitle.setText(message);
		Button btnRetry = (Button) viewWaring.findViewById(R.id.buttonRetry);
		btnRetry.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				switch (type) {
				case INT_RTYPE_FIRST:
					requestData(INT_RTYPE_REFRESH, 0);
					break;
				case INT_RTYPE_REFRESH:
					requestData(INT_RTYPE_REFRESH, 0);
					break;
				case INT_RTYPE_LODMORE:
					requestData(INT_RTYPE_LODMORE, mArrayList.size());
					break;
				}
				dialog.dismiss();
			}
		});
		Button btnCalcell = (Button) viewWaring.findViewById(R.id.buttonCancell);
		btnCalcell.setEnabled(isEnableCancell);
		btnCalcell.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
		dialog.setContentView(viewWaring);
		dialog.show();
	}

	/**
	 * 更新列表数据
	 * 
	 * @param datas
	 * @param rtype
	 */
	private void buildConsultAdapter(ArrayList<Topic> datas, int rtype) {

		try {
			switch (rtype) {
			case INT_RTYPE_FIRST:
				// 首次请求
				mArrayList.clear();// 数据清零
				mArrayList.addAll(datas);
				mAdapter = new TopicAdapter(getActivity(), mArrayList);
				mlistViewTopics.setAdapter(mAdapter);
				break;
			case INT_RTYPE_REFRESH:
				mArrayList.clear();// 数据清零
				mArrayList.addAll(datas);
				mAdapter.notifyDataSetChanged();
				break;
			case INT_RTYPE_LODMORE:
				mArrayList.addAll(datas);
				mAdapter.notifyDataSetChanged();
				break;
			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		mlistViewTopics.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
				if (0 != pos) {
					goToDetail(mArrayList.get(pos - 1));
				}
			}
		});
	}

	private void createheaderView() {
		headerView = View.inflate(getActivity(), R.layout.header_topic, null);
		mlistViewTopics.addHeaderView(headerView);
	}

	private void updateHeader(final Topic topic) {
		BackAsnycImageView imageViewFooterImg = (BackAsnycImageView) headerView.findViewById(R.id.imageViewFooterImg);
		imageViewFooterImg.setUrl(topic.getCoverImg());
		TextView textViewPeroid = (TextView) headerView.findViewById(R.id.textViewPeroid);
		textViewPeroid.setText("第" + topic.getPeriod() + " 期" + topic.getTitle());
		LogUtil.i(App.tag, "封面:" + topic.getCoverImg());
		headerView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				goToDetail(topic);
			}
		});
		
	}

	private void goToDetail(Topic topic) {
		currentTopic = topic;
		Intent i = new Intent();
		i.putExtra("topic", currentTopic);
		i.setClass(getActivity(), TopicDetailActivity.class);
		getActivity().startActivity(i);
	}

	@Override
	public void onClick(View v) {

	}

	@Override
	public void onFooterRefresh(PullToRefreshView view) {// 刷新
		mPullToRefreshView.postDelayed(new Runnable() {
			@Override
			public void run() {
				requestData(INT_RTYPE_LODMORE, mArrayList.size());
				mPullToRefreshView.onFooterRefreshComplete();
			}
		}, 1000);
	}

	@Override
	public void onHeaderRefresh(PullToRefreshView view) {// 加载更多
		mPullToRefreshView.postDelayed(new Runnable() {
			@Override
			public void run() {
				// 设置更新时间
				// mPullToRefreshView.onHeaderRefreshComplete("最近更新:01-23 12:01");
				requestData(INT_RTYPE_REFRESH, 0);
				mPullToRefreshView.onHeaderRefreshComplete();
			}
		}, 1000);

	}
}
